<template>
  <view
    class="tn-overlay"
    :class="{
      'tn-overlay--show': isShow,
      'tn-overlay--visible': isVisible
    }"
    :style="overlayStyle"
    @tap.stop="handleClick"
    @touchmove.stop.prevent="() => {}"

  >
    <slot></slot>
  </view>
</template>

<script lang="ts" setup>
import { overlayProps, overlayEmits } from '../../../types/tn-overlay'
import { computed, ref, watch, CSSProperties } from 'vue'

const props = defineProps(overlayProps)
const emits = defineEmits(overlayEmits)

// 标记组件是否存在
const isVisible = ref<boolean>(false)
// 标记组件是否显示
const isShow = ref<boolean>(false)

// overlay样式
const overlayStyle = computed<CSSProperties>(() => {
  let style: CSSProperties = {}

  // 设置动画执行时间
  if (props.duration !== 'undefined') {
    style.transition = `all ${props.duration}ms ease`
  }
  // 设置背景透明度
  let opacity: string | number = 0.2
  if (props.opacity !== 'undefined') {
    opacity = props.opacity
  }
  style.backgroundColor = `rgba(0, 0, 0, ${opacity})`
  if (props.zIndex !== 'undefined') {
    style.zIndex = Number(props.zIndex)
  }

  return Object.assign(style, props.customStyle || {})
})

// 状态定时器
let statusTimer: number | null = null
// 修改组件的状态
const changeComponentStatus = (status: boolean) => {
  resetStatusTimer()
  // 显示组件
  if (status === true) {
    isVisible.value = true
    isShow.value = true
    // nextTick(() => {
    //   statusTimer = setTimeout(() => {
    //     isShow.value = true
    //     resetStatusTimer()
    //   }, 20);
    // })
  } else {
    isShow.value = false
    isVisible.value = false
    // nextTick(() => {
    //   // 保证动画执行完毕再销毁
    //   statusTimer = setTimeout(() => {
    //     isVisible.value = false
    //     resetStatusTimer()
    //   }, Number(props.duration) || 250);
    // })
  }
}
// 重置状态定时器
const resetStatusTimer = () => {
  if (!statusTimer && statusTimer !== null) {
    clearTimeout(statusTimer)
    statusTimer = null
  }
}

// 监听show状态
watch(() => props.show, (nVal: boolean) => {
  if (nVal) {
    changeComponentStatus(true)
  } else {
    // 防止初始化时被执行
    if (isShow.value) {
      changeComponentStatus(false)
    }
  }
}, {
  immediate: true
})

// 处理点击事件
const handleClick = () => {
  emits('click')
}
</script>

<script lang="ts">
export default {
  options: {
    // 在微信小程序中将组件节点渲染为虚拟节点，更加接近Vue组件的表现(不会出现shadow节点下再去创建元素)
    virtualHost: true
  }
}
</script>

<style lang="scss" scoped>
.tn-overlay {
  position: fixed;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  transition: all 0.25s ease;
  // display: none;
  visibility: hidden;
  opacity: 0;

  &--show {
    opacity: 1;
  }
  &--visible {
    // display: block;
    visibility: visible;
  }
}
</style>
